<!--  -->
<template>
  <div id="main">
    <h2>权限管理</h2>

    <el-button
      type="primary"
      style="margin:20px"
      @click="handleOpen('添加权限', 1)"
      >添加权限</el-button
    >

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <!-- <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column> -->

        <el-table-column align="center" prop="jurisdictionId" label="权限Id" />

        <el-table-column
          align="center"
          prop="jurisdictionName"
          label="权限名称"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改权限', 2, Scope.row.jurisdictionId)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(Scope.row.jurisdictionId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      title="修改权限"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="jurisdiction"
        :model="jurisdiction"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="jurisdictionId"
          label="权限Id"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="jurisdiction.jurisdictionId"
            autocomplete="off"
            :readonly="readonly"
          />
        </el-form-item>

        <el-form-item
          prop="jurisdictionName"
          label="权限名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="jurisdiction.jurisdictionName"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('jurisdiction')"
          >修 改</el-button
        >
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddUser('jurisdiction')"
          >添 加</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getAllJurisdiction,
  deleteJurisdiction,
  getJurisdictionById,
  addJurisdiction,
  updateJurisdiction
} from "@/api/jurisdiction";
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      list: [],
      listLoading: false,
      editType: 1, // 1 添加 2 修改
      jurisdiction: {},
      dialogFormVisible: false,
      formLabelWidth: "200px",
      readonly: false,
      rules: {
        jurisdictionId: [
          { required: true, message: "权限Id不能为空", trigger: "blur" }
        ],
        jurisdictionName: [
          { required: true, message: "权限名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchData();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size;
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },
    handleClick(row) {
      console.log(row);
    },
    fetchData() {
      this.listLoading = true;
      getAllJurisdiction().then(resp => {
        this.list = resp.obj;
        this.listLoading = false;
      });
    },
    handleDelete(id) {
      this.$confirm("确认删除Id为" + id + "的权限？").then(() =>
        deleteJurisdiction(id).then(data => {
          this.$notify({
            title: "操作成功",
            type: "success"
          });
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize);
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage;
          this.currentPage = this.currentPage < 1 ? 1 : page;
          this.fetchData();
        })
      );
    },
    handleOpen(title, type, id) {
      this.readonly = false;
      this.jurisdiction = {};
      this.dialogFormVisible = true;
      this.title = title;
      this.editType = type;
      if (type === 2) {
        this.readonly = true;
        getJurisdictionById(id).then(resp => {
          this.jurisdiction = resp.obj;
        });
      }
    },
    handleClose() {
      this.dialogFormVisible = false;
      this.jurisdiction = {};
    },
    handleAddUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addJurisdiction(
            this.jurisdiction.jurisdictionId,
            this.jurisdiction.jurisdictionName
          ).then(resp => {
            this.$notify({
              title: "操作成功",
              type: "success"
            });
            this.fetchData();
          });
          this.dialogFormVisible = false;
          return true;
        } else {
          this.$notify({
            title: "请正确填写",
            type: "error"
          });
          return false;
        }
      });
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          updateJurisdiction(
            this.jurisdiction.jurisdictionId,
            this.jurisdiction.jurisdictionName
          ).then(resp => {
            this.$notify({
              title: "修改成功",
              type: "success"
            });
            this.fetchData();
          });
          this.dialogFormVisible = false;
          return true;
        } else {
          this.$notify({
            title: "请正确填写",
            type: "error"
          });
          return false;
        }
      });
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
#search-card {
  line-height: 0px;
  margin-left: 10px;
  text-align: left;
  width: 100%;
  height: 70px;
  overflow-x: hidden;
}
</style>
